package com.qf.lanzhou.blog.api.dao.Impl;

import com.qf.lanzhou.blog.api.common.Number;
import com.qf.lanzhou.blog.api.dao.ArticlePaginationDao;
import com.qf.lanzhou.blog.api.pojo.entity.Article;
import com.qf.lanzhou.blog.api.pojo.entity.FeedbackEntity;
import com.qf.lanzhou.blog.api.pojo.entity.Page;
import com.qf.lanzhou.blog.api.util.BeanProcessor;
import com.qf.lanzhou.blog.api.util.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author jack
 */
public class ArticlePaginationDaolmpl implements ArticlePaginationDao {
    private QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
    @Override
    public List defaultPagination(Page page) {
        String sql = "SELECT * FROM `t_article`LIMIT ?,?;";
        return getList(page, sql);
    }


    @Override
    public Long selectCount() {
        String sql ="select count(*) from t_article;";
        ScalarHandler<Long> handler = new ScalarHandler<>();
        try {
            Long query = queryRunner.query(sql, handler);
            return  query;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List kudosPagination(Page page) {
        String sql="SELECT * FROM `t_article`ORDER BY article_like DESC LIMIT ?,?;";
        return getList(page,sql);
    }

    private List<Article> getList(Page page, String sql) {
        Object[] parm = {page.getStartRow(),page.getPageSize()};
        BeanListHandler<Article> beanListHandler = BeanProcessor.getBeanListHandler(Article.class);
        try {
            List<Article> list =  queryRunner.query(sql, beanListHandler, parm);
            ArticleDaoImp instance = ArticleDaoImp.getInstance();
            for (Article article:list) {
                Long sumPrice = instance.getSumPrice(article.getArticleId());
                article.setArticleLike(sumPrice);
                article.setArticleProduce(article.getArticleCreatetime());
            }
            return  list;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
}
